package com.fdb.basic.framework.core.dubbo.filter;

import com.fdb.basic.framework.core.util.StringUtility;
import com.fdb.basic.framework.core.util.TraceUtil;
import org.apache.logging.log4j.ThreadContext;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;

/**
 * @description:在c和p之间传递TraceId的过滤器
 * @date:2019年1月28日 上午11:21:12
 * @author:hengyh
 */
@Activate(group = { Constants.CONSUMER, Constants.PROVIDER })
public class TraceFilter implements Filter {

	/**
	 * 0.2:huangwb:2019年3月4日 下午2:55:08:增加交易码 <br>
	 * 
	 * @param invoker
	 * @param invocation
	 * @return
	 * @throws RpcException
	 * @author hengyh
	 * @author huangwb
	 * @since 2019年1月28日 上午11:21:12
	 * @date 2019年3月4日 下午2:55:08
	 * @version 1.1
	 */
	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
		String traceId = RpcContext.getContext().getAttachment(TraceUtil.TRACEID);
		if (!StringUtility.isEmpty(traceId)) {
			TraceUtil.setTraceId(traceId);
		} else {
			RpcContext.getContext().setAttachment(TraceUtil.TRACEID, TraceUtil.getTraceId());
		}
		String platdmId = RpcContext.getContext().getAttachment(TraceUtil.PLATFMID);
		if (!StringUtility.isEmpty(platdmId)) {
			TraceUtil.setPlafmID(platdmId);
		} else {
			RpcContext.getContext().setAttachment(TraceUtil.PLATFMID, TraceUtil.getPlafmID());
		}
		String platfmUsrId = RpcContext.getContext().getAttachment(TraceUtil.PLAFMUSRID);
		if (!StringUtility.isEmpty(platfmUsrId)) {
			TraceUtil.setPlafmUsrID(platfmUsrId);
		} else {
			RpcContext.getContext().setAttachment(TraceUtil.PLAFMUSRID, TraceUtil.getPlafmUsrID());
		}
		String cnsmrTxnCd = RpcContext.getContext().getAttachment(TraceUtil.CNSMRTXNCD);// 交易码
		if (!StringUtility.isEmpty(cnsmrTxnCd)) {
			TraceUtil.setCnsmrTxnCd(cnsmrTxnCd);
		} else {
			RpcContext.getContext().setAttachment(TraceUtil.CNSMRTXNCD, TraceUtil.getCnsmrTxnCd());
		}
		ThreadContext.put(TraceUtil.TRACEID, TraceUtil.getTraceId());
		ThreadContext.put(TraceUtil.CNSMRTXNCD, TraceUtil.getCnsmrTxnCd());
		return invoker.invoke(invocation);
	}

}
